/**
 * @description 封装请求拦截器和响应拦截器(微信小程序版)
 * @author 十一
 * @date 2022-11-14 13:18
 */

import uniRequest from "../../node_modules/uni-request/index";
import storage from "../storage/storageHelper";
import api from "./api";

/**
 * 开发环境
 * @type {string}
 */
let devApiPath = "https://localhost:44366/api/";

/**
 * 配置请求根路径
 * @type {string}
 */
uniRequest.defaults.baseURL = devApiPath;

/**
 * 需要Token的api
 * @type {*[]}
 */
let needTokenApi = [];
let apiArr = Object.keys(api).map((i) => {
    return api[i];
});
apiArr.forEach((item) => {
    if (item.needToken == true) {
        needTokenApi.push(item.url);
    }
});

/**
 * 添加请求拦截
 */
uniRequest.interceptors.request.use(
    config => {
        // 配置请求头，JSON格式发送
        config.headers = {
            "Content-Type": "application/json"
        };
        // 如果请求接口需要token验证
        if (needTokenApi.includes(config.url)) {
            let tokenStr = storage.get("token");
            if (tokenStr === "键值不存在：token") {
                uni.showToast({
                    title: "登录超时",
                    icon: "error",
                    duration: 2500
                });
                setTimeout(() => {
                    // uni.reLaunch({
                    //     url: "/pages/login/login"
                    // });
                }, 2501);
            } else {
                config.headers.Authorization = "Bearer " + tokenStr.token;  // 配置请求头(Bearer token)
            }
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

/**
 * 添加响应拦截器
 */
uniRequest.interceptors.response.use(
    response => {
        if (response.data.message === "Token:OK") {
            let tokenPara = {
                userID: response.data.data.userID,
                token: response.data.data.token,
            };
            storage.set("token", JSON.stringify(tokenPara), response.data.data.expires);
        }
        return Promise.resolve(response.data);
    },
    error => {
        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = "错误请求";
                    break;
                case 401:
                    error.message = "登录超时，请重新登录";
                    break;
                case 403:
                    error.message = "拒绝访问";
                    break;
                case 404:
                    error.message = "请求错误，为找到该资源";
                    break;
                case 405:
                    error.message = "请求方法错误";
                    break;
                case 408:
                    error.message = "请求超时";
                    break;
                case 500:
                    error.message = "服务端错误";
                    break;
                case 501:
                    error.message = "网络未实现";
                    break;
                case 502:
                    error.message = "网络错误";
                    break;
                case 503:
                    error.message = "服务不可用";
                    break;
                case 504:
                    error.message = "网络超时";
                    break;
                case 505:
                    error.message = "http版本不支持该请求";
                    break;
                default:
                    error.message = `连接错误${error.response.status}`;
            }
        } else {
            // 超时处理
            if (JSON.stringify(error).includes("timeout")) {
                uni.showToast({
                    title: "服务器响应超时，请刷新当前页",
                    icon: "error",
                    duration: 2000
                });
            }
            error.message = "连接服务器失败";
        }
        console.log(error)
        return Promise.reject(error.response);
    }
);

export default uniRequest;
